Use map to loop over a collection and apply the same
operation to each element in the collection. It returns after
applying transform.
let arrInt = [1,8,4,6]
I want add 1 in every number in array.
Without loop, using map,
arrInt.map( $0 + 1) // <- This is shortest code for doing map
output : [2,9,5,7]
How map works :
The map function has a single argument which is a closure (a
function) that it calls as it loops over the collection. This
closure takes the element from the collection as an argument and
returns a result. The map function returns these results in an
array.
Another example :
let chocolateAmt = [“Dairy Milk”:20.0, “Munch”:10]
I want to increase price 5%,
so using map,
chocolateAmt.map{ (key, value) in
value + value*0.05
}
output : [“Dairy Milk”:21.0, “Munch”:10.5]
Another Example :
If we want index in map,
let arrInt = [1, 2, 4, 5]
let indexElement = arrInt.enumerated().map { (index,element) in
return "\(index):\(element)"
}
print(indexElement) // [“0:1”, “1:2”, “2:4”, “3:5”]
CompactMap: Use this method to receive an array of nonoptional values when your transformation produces an optional value.
let scores = ["1", "2", "three", "four", "5"]
let mapped: [Int?] = scores.map { str in Int(str) }
// [1, 2, nil, nil, 5] - Two nil values as "three" and "four" are strings.
let compactMapped: [Int] = scores.compactMap { str in Int(str) }
// [1, 2, 5] - The nil values for "three" and "four" are filtered out.
FlatMap : Flatmap is used to flatten a collection of collections.
Flatmap is joined word of Flat + Map. So as per name, it applies map function over collection and do flatten collection.
Test 1 :
let codes = [["abc","def","ghi"],["jkl","mno","pqr"]]
let newCodes = codes.flatMap { $0.map {$0.uppercased()} }
print(newCodes)
Output : ["ABC","DEF","GHI","JKL","MNO","PQR"]
Test 2 :
let codes = ["abc","def","ghi"]
let newCodes = codes.flatMap { $0.uppercased() }
print(newCodes)
Output : ["A","B","C","D","E","F","G","H","I"]
-> In Test 2, first it applies map so half output is like
["ABC","DEF","GHI"] and after that it applies flat so now full
output is : ["A","B","C","D","E","F","G","H","I"]
Tip :
1. String is collection from Swift 4.
2.If you do flatmap a collection containing optional values,
flatmap will only consider the non-nil values.
let codes = [1,2,nil,3,nil,5]
let newCodesFlatMap = codes.flatMap { return $0 }
output : [1,2,3,5]
let newCodesFlatMap = codes.map { return $0 }
output : [optional(1),optional(2),nil,optional(3),nil,optional(5)]
The output of map became a collection of optional int ([Int?])
only because the array had nil — value in it. Otherwise it would
have been an Int array. It is benefit of using flatMap.
Filter : Return array with elements
which fulfill filter condition.